<?php
	namespace Admin\Controller;
	use Think\Controller;
	/**
	 * @author dongtian <dongtian@nuaa.edu.cn>
	 * 产品类别控制器
	 */

	class CategoryController extends CommonController {
		/**
		 * 种类列表显示
		 */
		public function listView (){
			$this->title = '产品种类列表';
			$category_model = M('categories');
			$p = I('get.p',1,'intval');
			$count = $category_model->count();
			$list = $category_model->page($p . ',8')->select();
			$Page = new \Think\Page($count,8);//实例化分页类
			$Page->setConfig('header','个类别');
			$Page->setConfig('prev','上一页');
			$Page->setConfig('next','下一页');
			$Page->setConfig('first','第一页');
			$Page->setConfig('last','最后页');
			$page = $Page->show();
			$this->categories = $list;
			$this->page = $page;
 			$this->display();
		}
		/**
		 * 产品类别详情
		 */
		public function view (){
			$id = I('get.id','','intval');
			$map['id'] = $id;
			$result = M('categories')->where($map)->find();
			if($result){
				$this->category = $result;
				$this->display();
			}else{
				$this->error('该产品类别不存在');
			}
		}
		/**
		 * 添加视图
		 */
		public function add (){
			$this->title = '添加产品类别';
			$this->display();
		}

		/**
		 * 执行添加
		 */
		public function addDo (){
			$data = I('post.');
			$result = M('categories')->add($data);
			if($result){
				$this->success('添加成功',U('Admin/category/listView'));
			}else{
				$this->error('添加失败');
			}
		}

		/**
		 * 编辑视图
		 */
		public function edit (){
			$this->title = '产品类别编辑';
			$id = I('get.id','','intval');
			$map['id'] = $id;
			$result = M('categories')->where($map)->find();
			if($result){
				$this->category = $result;
				$this->display();
			}else{
				$this->error('该产品类别不存在');
			}
		}

		/**
		 * 执行编辑
		 */
		public function editDo (){
			$data = I('post.');
			$result = M('categories')->save($data);
			if($result){
				$this->success('修改成功',U('Admin/Category/listView'));
			}else{
				$this->error('修改失败');
			}
		}

		/**
		 * 删除，同时删除该产品类别下的所有产品记录
		 */
		
		public function delete (){
			$id = I('get.id','','intval');
			$map['type_id'] = $id;
			$result1 = D('ProductRelation')->relation('product_type')->where($map)->delete();
			$result2 = M('categories')->where(array('id'=>$id))->delete();
			if($result1 && $result2){
				$this->success('删除成功',U('Admin/Category/listView'));
			} else{
				$this->error('删除失败');
			}
		}
	}
?>